<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">-->
    <title>生成像素对象</title>
</head>
<body>
<p>自己循环对Uint8ClampedArray赋值，有问题，超过一定大小赋值不成功。原因不明</p>

<canvas id="canvas" width="300" height="300"></canvas>
<canvas id="canvas2" width="1024" height="1024"></canvas>
<script>


    function draw() {
//自己循环对Uint8ClampedArray赋值，有问题，超过一定大小赋值不成功。原因不明
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        var width = canvas.width;
        var height = canvas.height;

        var data = new Uint8ClampedArray(width * height * 4);
        // var data = [];
        for (var i = 0; i < height; i += 4) {
            for (var j = 0; j < width; j += 4) {
                var gray = (256 * (i * width + j) / (width * height));
                data[i * width + j] = gray;
                data[i * width + j + 1] = gray;
                data[i * width + j + 2] = gray;
                data[i * width + j + 3] = 255;

                // if (i % 100 === 0) {
                //     console.log(gray, i);
                // }
            }
        }
        console.log(data);
        console.log(new Date().getTime() - startTime);

        var startTime = new Date().getTime();
        ctx.putImageData(new ImageData(data, width, height), 0, 0);
        console.log(new Date().getTime() - startTime);

    }


    function draw2() {

        var canvas = document.getElementById("canvas2");
        var ctx = canvas.getContext("2d");
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        console.log(imgData.data);

    }


    draw();
    draw2();

</script>
</body>

</html>